 <template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="pd.showSearch">
        <el-form :model="pd.queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="订单名称" prop="name">
            <el-input v-model="pd.queryParams.name" placeholder="请输入订单名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="产品名称" prop="productName">
            <el-input v-model="pd.queryParams.productName" placeholder="请输入产品名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="交货时间" prop="deliveryTime">
            <el-date-picker clearable
              v-model="pd.queryParams.deliveryTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择交货时间"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['wms:schedule:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="pd.single" @click="handleUpdate()" v-hasPermi="['wms:schedule:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="pd.multiple" @click="handleDelete()" v-hasPermi="['wms:schedule:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['wms:schedule:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="pd.showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="pd.loading" :data="pd.scheduleList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="计划名称" align="center" prop="name" />
        <el-table-column label="订单名称" align="center" prop="orderName" />
        <el-table-column label="产品名称" align="center" prop="productName" />
        <el-table-column label="交货时间" align="center" prop="deliveryTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.deliveryTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="wms_schedule_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" prop="quantity" />
        <el-table-column label="完成量" align="center" prop="quantityFinished" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column fixed="left" label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['wms:schedule:edit']">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['wms:schedule:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="pd.total>0" :total="pd.total" v-model:page="pd.queryParams.pageNum"
                  v-model:limit="pd.queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改生产计划排程对话框 -->
    <el-dialog :title="pd.dialog.title" v-model="pd.dialog.visible" width="700px" append-to-body>
      <el-form ref="scheduleFormRef" :model="pd.form" :rules="pd.rules" label-width="80px">
        <el-row :gutter="10" class="mb8" style="justify-content:space-evenly">
          <el-col :span="11">
            <el-form-item label="选择订单">
              <OrderSearch :dataText="pd.orderName" :searchType="1" :params="{typeId:8,status:'3'}" @ok="lineAdd" title="待出库物品订单" />
            </el-form-item>
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="pd.form.productName" placeholder="请输入产品名称" />
            </el-form-item>
            <el-form-item label="产品id" prop="productId">
              <el-input v-model="pd.form.productId" placeholder="请输入产品id" disabled />
            </el-form-item>
            <el-form-item label="订单id" prop="orderId">
              <el-input v-model="pd.form.orderId" placeholder="请输入订单id" disabled />
            </el-form-item>
            <el-form-item label="物料清单" prop="bomId">
              <BomSearch :params="{productId:pd.form.productId}" :data-text="pd.form.bomName" :searchType="1" @ok="lineAddBom" title="请选择物料" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="计划名称" prop="name">
              <el-input v-model="pd.form.name" placeholder="请输入计划名称" />
            </el-form-item>
            <el-form-item label="数量" prop="quantity">
              <el-input v-model="pd.form.quantity" placeholder="请输入数量" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="pd.form.status">
                <el-radio
                  v-for="dict in wms_schedule_status"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.name}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="交货时间" prop="deliveryTime">
              <el-date-picker clearable
                v-model="pd.form.deliveryTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择交货时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="23">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="pd.form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="pd.buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="选择销售单" v-model="pd.orderDialog.visible">
      <el-table @select="selectOrder" v-loading="pd.loading" :data="pd.line" ref="refTable">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="物品名称" align="center" prop="productName" />
        <el-table-column label="单位" align="center" prop="measureUnit" width="60" />
        <el-table-column label="价格" align="center" prop="price" width="80" />
        <el-table-column label="库存" align="center" prop="maxQuantity" width="80" />
        <el-table-column label="数量" align="center" prop="quantity" width="80" />
        <el-table-column label="总金额" align="center" prop="totalMoney" width="80" />
        <el-table-column label="优惠金额" align="center" prop="quantity" width="120" />
        <el-table-column label="应收金额" align="center" prop="costMoney" width="120" />
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleLineSelected">确 定</el-button>
          <el-button @click="pd.orderDialog.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Schedule" lang="ts">
import {ScheduleVO, listSchedule, delSchedule, addSchedule, updateSchedule } from '@/views/wms/schedule/api';
import OrderSearch from "@/views/wms/order/search.vue";
import {listOrderLine, OrderLineVO, OrderVO} from "@/views/wms/order/api";
import BomSearch from "@/views/wms/bom/search.vue";
import {BomVO} from "@/views/wms/bom/api";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const {wms_schedule_status} = toRefs<any>(proxy?.useDict('wms_schedule_status'));


const queryFormRef = ref<ElFormInstance>();
const scheduleFormRef = ref<ElFormInstance>();

const pd = reactive({
  scheduleList: <ScheduleVO[]>([]),
  buttonLoading: false,
  loading: true,
  showSearch: true,
  selectVO: <ScheduleVO[]>([]),
  single: true,
  multiple: true,
  total: 0,
  form: <ScheduleVO>{},
  orderName: '',
  line: [] as any,
  queryParams: <ScheduleVO>{
    pageNum: 1,
    pageSize: 10,
    orderId: undefined,
    productId: undefined,
    deliveryTime: undefined,
    params: {
    }
  },
  rules: <ElFormRules>{
    id: [
      { required: true, message: "计划id不能为空", trigger: "blur" }
    ],
    orderId: [
      { required: true, message: "订单id不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "计划名称不能为空", trigger: "blur" }
    ],
    productId: [
      { required: true, message: "产品id不能为空", trigger: "blur" }
    ],
    deliveryTime: [
      { required: true, message: "交货时间不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    quantity: [
      { required: true, message: "数量不能为空", trigger: "blur" }
    ],
    bomId: [
      { required: true, message: "BOM不能为空", trigger: "blur" }
    ]
  },
  dialog: <DialogOption>{
    visible: false,
    title: ''
  },
  orderDialog: <DialogOption>{
    visible: false,
    title: ''
  }
});

// const { queryParams, form, rules } = toRefs(data);

/** 查询生产计划排程列表 */
async function getList() {
  pd.loading = true;
  const res = await listSchedule(pd.queryParams);
  pd.scheduleList = res.rows;
  pd.total = res.total;
  pd.loading = false;
}

/** 取消按钮 */
function cancel() {
  reset();
  pd.dialog.visible = false;
}

/** 表单重置 */
function reset() {
  pd.form = {};
  scheduleFormRef.value?.resetFields();
  pd.line = [];
}

/** 搜索按钮操作 */
function handleQuery() {
  pd.queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: ScheduleVO[]) {
  pd.selectVO = selection;
  pd.single = selection.length != 1;
  pd.multiple = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  pd.orderName = '';
  pd.form.status = '0';
  pd.dialog.visible = true;
  pd.dialog.title = "添加生产计划排程";
}

/** 修改按钮操作 */
async function handleUpdate(row?: ScheduleVO) {
  reset();
  const data = row || pd.selectVO[0]
  Object.assign(pd.form, data);
  pd.orderName = row?.orderName || '';
  pd.dialog.visible = true;
  pd.dialog.title = "修改生产计划排程";
}

/** 提交按钮 */
function submitForm() {
  scheduleFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      pd.buttonLoading = true;
      if (pd.form.id) {
        await updateSchedule(pd.form).finally(() =>  pd.buttonLoading = false);
      } else {
        await addSchedule(pd.form).finally(() =>  pd.buttonLoading = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      pd.dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
async function handleDelete(row?: ScheduleVO) {
  const _ids = row?.id || pd.selectVO.map(v => v.id);
  await proxy?.$modal.confirm('是否确认删除生产计划排程编号为"' + _ids + '"的数据项？').finally(() => pd.loading = false);
  await delSchedule(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
function handleExport() {
  proxy?.download('wms/schedule/export', {
    ...pd.queryParams
  }, `schedule_${new Date().getTime()}.xlsx`)
}
/** 选择订单 */
async function lineAdd(vo: OrderVO) {
  const vvo = JSON.parse(JSON.stringify(vo));
  pd.orderName = vvo[0].name
  const data = JSON.parse(JSON.stringify(vo))
  let line: OrderLineVO = {};
  pd.line = [];
  line.id = data[0].id;
  line.whId = data[0].selfWhId;
  let res: OrderLineVO[] = [];
  await listOrderLine(line).then((result)=>{
    res = result.rows;
  });
  res.forEach((v, i, a) => {
    line.id = v.id;
    line.productId = v.productId;
    line.productName = v.productName;
    line.price = v.price ? v.price : 0;
    line.measureUnit = v.measureUnit;
    line.quantity = v.quantity;
    line.maxQuantity = v.stockQuantity;
    line.totalMoney = v.price ? v.price : 0;
    line.discountMoney = v.discountMoney ? v.discountMoney : 0;
    line.costMoney = line.discountMoney ? line.totalMoney - line.discountMoney : line.totalMoney * line.quantity!;
    line.whName = data.warehouseName;
    line.whId = data.warehouseId;
    pd.line.push(line);
    line = {};
  });
  // 打开选择窗口
  pd.orderDialog.visible = true;
}

function handleLineSelected() {
  pd.line = (proxy?.$refs['refTable'] as any).getSelectionRows();
  if (pd.line.length === 0) {
    proxy?.$modal.msgError('请选择一行数据！');
    return;
  }
  pd.form.orderId = pd.line[0].id;
  pd.form.productId = pd.line[0].productId;
  pd.form.productName = pd.line[0].productName;
  pd.form.quantity = pd.line[0].quantity
  pd.orderDialog.visible = false;
  pd.line = [];
  // 选择订单产品后，BOM要清空重选
  pd.form.bomId = undefined;
  pd.form.bomName = undefined;
}
function selectOrder(selection: OrderVO[], row: OrderVO[]) {
  //清空选项
  (proxy?.$refs['refTable'] as any).clearSelection();
  //将这行选中
  (proxy?.$refs['refTable'] as any).toggleRowSelection(row, true);
}

/** 选择物料清单 */
function lineAddBom(vo: BomVO) {
  const data = JSON.parse(JSON.stringify(vo))
  pd.form.bomId = data[0].id;
  pd.form.bomName = data[0].name;
}

onMounted(() => {
  getList();
});
</script>
